import 'package:flutter/material.dart';
import 'package:kasax_demos2/entry/data_posts_test.dart';
import 'package:kasax_demos2/entry/entrys.dart';

/// DataTable 使用
class DatatableDemo extends StatefulWidget {
  const DatatableDemo({Key? key}) : super(key: key);

  @override
  _DatatableDemoState createState() => _DatatableDemoState();
}

class _DatatableDemoState extends State<DatatableDemo> {
  int _sortColumnIndex = 0;

  // 是否升序
  bool _sortAscending = true;

  List<Posts> _list = PostsDatas.TEST_POSTS;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Datatable示例"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: SingleChildScrollView(
          child: DataTable(
            columnSpacing: 8,
            sortColumnIndex: _sortColumnIndex,
            sortAscending: _sortAscending,
            horizontalMargin: 8,
            dataRowHeight: 120,
            showBottomBorder: true,
            columns: [
              DataColumn(
                  label: Text("title"),
                  onSort: (int columnIndex, bool ascending) {
                    setState(() {
                      _sortColumnIndex = columnIndex;
                      _sortAscending = ascending;
                      // 排序
                      _list.sort((a, b) {
                        if (!ascending) {
                          final c = a;
                          a = b;
                          b = c;
                        }
                        return a.title.length.compareTo(b.title.length);
                      });
                    });
                  }),
              DataColumn(label: Text("author")),
              DataColumn(label: Text("image")),
            ],
            rows: _list.map((e) {
              return DataRow(
                  selected: e.selected, // 选中状态
                  onSelectChanged: (selected) {
                    setState(() {
                      // 处理选中
                      if (e.selected != selected) e.selected = selected!;
                    });
                  },
                  cells: [
                    DataCell(
                      Text("${e.title}"),
                    ),
                    DataCell(Text("${e.author}")),
                    DataCell(Padding(
                      padding: EdgeInsets.all(10),
                      child: Image.network(
                        e.imageUrl,
                        fit: BoxFit.cover,
                      ),
                    )),
                  ]);
            }).toList(),
          ),
        ),
      ),
    );
  }
}
